package com.fish.passport.processor.impl;

import java.util.Date;

import org.apache.commons.lang.time.DateUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.fish.passport.po.PassCode;
import com.fish.passport.processor.ApplyCodeProcessor;
import com.fish.passport.processor.DestroyCodeProcessor;
import com.fish.passport.processor.UpdateContentProcessor;
import com.fish.passport.processor.impl.client.gmedia.GmediaServiceClient;
import com.fish.passport.processor.impl.client.gmedia.GmediaUtil;
import com.fish.passport.processor.impl.client.gmedia.model.Body;
import com.fish.passport.processor.impl.client.gmedia.model.Head;
import com.fish.passport.processor.impl.client.gmedia.model.Request;
import com.fish.passport.processor.impl.client.gmedia.model.Response;
import com.fish.vo.Passport;
import com.fish.vo.PassportConstant;

/**
 * 银河第三方接口实现
 * 
 * @author chenlinjun
 * 
 */
public class GmediaProcessorImpl implements ApplyCodeProcessor, DestroyCodeProcessor, UpdateContentProcessor {
	private static final Log log = LogFactory.getLog(GmediaProcessorImpl.class);
	private static final String STATU="100";
	
	@Override
	public Passport apply(PassCode passCode) {
		log.info("Gmedia Apply Code Request :"+passCode.getSerialNo());
		GmediaServiceClient client = GmediaServiceClient.getClientInstance();
		String uuid=passCode.getSerialNo();
		String date=GmediaUtil.dateToString(passCode.getCreateTime());
		String timeStamp=date;
		String dealTime=date;
		//请求头信息
		Head head=new Head(passCode);
		head.setSequenceId(uuid);
		head.setTimeStamp(timeStamp);
		head.setDealTime(dealTime);
		head.setSigned(head.makeSignedForApplyCode());
		//消息体信息
		Body body=new Body(passCode);
		body.setTimeStamp(timeStamp);
		body.setDealTime(dealTime);
		//整个请求信息
		Request request=new Request();
		request.setHead(head);
		request.setBody(body);
		Passport passport=new Passport();
		try{
			String result=client.execute(request.toApplayCodeRequestXml(), "applyCodeReq");
			log.info("Gmedia ApplyCode Reqeust Result:"+result);
			//String result=StringUtil.getTestData();
			//返回值处理
			Response response=GmediaUtil.getResponse(result);
			head=response.getHead();
			body=GmediaUtil.getResponseBody(response.getBody());
			passport.setSerialno(passCode.getSerialNo());
			passport.setCode(body.getTCode());
			passport.setAddCode(body.getAssistCode());
			passport.setErrorNO(PassportConstant.PASSCODE_ERROR.APPLY.name());
			passport.setSendSms(PassportConstant.PASSCODE_SMS_SENDER.LVMAMA.name());
			passport.setSendOrderid(true);
			passport.setEventType(PassportConstant.PASSCODE_TYPE.APPLAYCODE.name());
			
			if (STATU.equals(head.getStatusCode().trim())) {
				passport.setStatus(PassportConstant.PASSCODE_STATUS.SUCCESS.name());
			}else{
				log.info("NewLand Applay Result status: " + head.getStatusCode());
				passport.setComLogContent("GmediaProcessorImpl_apply_Received an abnormal status code " + head.getStatusCode().trim());
				this.reapplySet(passport, passCode.getReapplyCount(), passport.getStatus());
			}
		}catch(Exception e){
			log.error("Gmedia ApplyCode Exception:",e);
			String error=e.getMessage();
			passport.setErrorNO(PassportConstant.PASSCODE_ERROR.APPLY.name());
			passport.setComLogContent(error);
			this.reapplySet(passport, passCode.getReapplyCount(), error);
		}

		return passport;
	}

	/**
	 * 重新申请码处理
	 * @param passport
	 * @param error
	 */
	public void reapplySet(Passport passport,long times,String error ){
		int reapplyMinute=0;
		if(error!=null){
			if(error.indexOf("Could not invoke service")!=-1){
				if(times==0){
					reapplyMinute=3;
				}else{
					reapplyMinute=10;
				}
			//Connection timed out
			}else if(error.indexOf("Connection")!=-1){
				reapplyMinute=2;
			//WSDLException: faultCode=PARSER_ERROR:
			}else if(error.indexOf("WSDLException")!=-1){
				if(times==0){
					reapplyMinute=2;
				}else{
					reapplyMinute=10;
				}
			}else if(error.indexOf("FAILED")!=-1){
				reapplyMinute=2;
			}
		}
		if(reapplyMinute>0 && times<3){
			passport.setReapplyTime(DateUtils.addMinutes(new Date(), reapplyMinute));
			passport.setStatus(PassportConstant.PASSCODE_STATUS.TEMP_FAILED.name());
		}else{
			passport.setStatus(PassportConstant.PASSCODE_STATUS.FAILED.name());
		}
	}
	
	@Override
	public Passport destroy(PassCode passCode) {
		log.info("Gmedia Destroy Code Request :"+passCode.getSerialNo());
		GmediaServiceClient client = GmediaServiceClient.getClientInstance();
		Head head=new Head(passCode);
		String uuid=passCode.getSerialNo();
		String date=GmediaUtil.dateToString(passCode.getCreateTime());
		String timeStamp=date;
		String dealTime=date;
		head.setSequenceId(uuid);
		head.setTimeStamp(timeStamp);
		head.setDealTime(dealTime);

		head.setSigned(head.makeSignedForDestoyCode());
		Body body=new Body(passCode);
		body.setTimeStamp(timeStamp);
		body.setDealTime(dealTime);
		Request request=new Request();
		request.setHead(head);
		request.setBody(body);
		
		Passport passport=new Passport();
		passport.setEventType(PassportConstant.PASSCODE_TYPE.DESTROYCODE.name());
		passport.setSerialno(uuid);
		try{
			String result=client.execute(request.toDestoyCodeRequestXml(),"sendDiscardReq");
			log.info("Gmedia destroyCode Request Result ："+result);
			//返回值处理
			Response response=GmediaUtil.getResponse(result);
			head=response.getHead();
			body=GmediaUtil.getResponseBody(response.getBody());
			if(STATU.equals(head.getStatusCode().trim())) {
				passport.setStatus(PassportConstant.PASSCODE_STATUS.SUCCESS.name());
			} else {
				passport.setStatus(PassportConstant.PASSCODE_STATUS.FAILED.name());
				passport.setErrorNO(PassportConstant.PASSCODE_ERROR.DESTROY.name());
				passport.setComLogContent("GmediaProcessorImpl_destroy_Received an abnormal status code " + head.getStatusCode().trim());
			}
		}catch(Exception e){
			log.error("Gmedia Destroy Exception:",e);
			passport.setStatus(PassportConstant.PASSCODE_STATUS.FAILED.name());
			passport.setComLogContent(e.getMessage());
			passport.setErrorNO(PassportConstant.PASSCODE_ERROR.DESTROY.name());
		}
		return passport;
	}

	@Override
	public Passport update(PassCode passCode) {
		Passport passport=new Passport();
		passport.setSerialno(passCode.getSerialNo());
		passport.setUpdatePrintContent(passCode.getUpdateTerminalContent());
		passport.setStatus(PassportConstant.PASSCODE_STATUS.SUCCESS.name());
		return passport;
	}

}
